<template>
  <div class="model-provider-management">
    <!-- 搜索和操作栏 -->
    <div class="mb-4 flex justify-between items-center">
      <div class="flex items-center space-x-4">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索供应商名称..."
          class="px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
        <button
          @click="handleSearch"
          class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
        >
          搜索
        </button>
      </div>
      <button
        @click="showAddModal = true"
        class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600"
      >
        添加供应商
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              供应商名称
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              供应商类型
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              配额类型
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              配额限制
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              状态
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              操作
            </th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="provider in providers" :key="provider.id">
            <td class="px-6 py-4 whitespace-nowrap">
              {{ provider.provider_name }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              {{ provider.provider_type }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              {{ provider.quota_type }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              {{ provider.quota_limit }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <span
                :class="provider.is_valid ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
              >
                {{ provider.is_valid ? '有效' : '无效' }}
              </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
              <button
                @click="editProvider(provider)"
                class="text-indigo-600 hover:text-indigo-900 mr-3"
              >
                编辑
              </button>
              <button
                @click="showModels(provider)"
                class="text-blue-600 hover:text-blue-900 mr-3"
              >
                模型管理
              </button>
              <button
                @click="deleteProvider(provider.id)"
                class="text-red-600 hover:text-red-900"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑供应商模态框 -->
    <div v-if="showAddModal || showEditModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white rounded-lg p-6 w-96">
        <h2 class="text-xl font-semibold mb-4">
          {{ showAddModal ? '添加供应商' : '编辑供应商' }}
        </h2>
        <form @submit.prevent="handleSubmit">
          <div class="mb-4">
            <label class="block text-gray-700 text-sm font-bold mb-2">
              供应商名称
            </label>
            <input
              v-model="formData.provider_name"
              type="text"
              class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm font-bold mb-2">
              供应商类型
            </label>
            <select
              v-model="formData.provider_type"
              class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            >
              <option value="ollama">Ollama</option>
              <option value="openai">OpenAI</option>
              <option value="anthropic">Anthropic</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm font-bold mb-2">
              配额类型
            </label>
            <select
              v-model="formData.quota_type"
              class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="token">Token</option>
              <option value="request">Request</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm font-bold mb-2">
              配额限制
            </label>
            <input
              v-model="formData.quota_limit"
              type="number"
              class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div class="mb-4">
            <label class="flex items-center">
              <input
                type="checkbox"
                v-model="formData.is_valid"
                class="form-checkbox h-5 w-5 text-blue-600"
              />
              <span class="ml-2 text-gray-700">是否有效</span>
            </label>
          </div>
          <div class="flex justify-end space-x-3">
            <button
              type="button"
              @click="closeModal"
              class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
            >
              取消
            </button>
            <button
              type="submit"
              class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
            >
              保存
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 模型管理模态框 -->
    <div v-if="showModelModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white rounded-lg p-6 w-3/4 max-w-4xl">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold">
            模型管理 - {{ currentProvider.provider_name }}
          </h2>
          <button
            @click="showAddModelModal = true"
            class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600"
          >
            添加模型
          </button>
        </div>
        
        <!-- 模型列表 -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  模型名称
                </th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  模型类型
                </th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="model in providerModels" :key="model.id">
                <td class="px-6 py-4 whitespace-nowrap">
                  {{ model.model_name }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  {{ model.model_type }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span
                    :class="model.is_valid ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                  >
                    {{ model.is_valid ? '有效' : '无效' }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <button
                    @click="editModel(model)"
                    class="text-indigo-600 hover:text-indigo-900 mr-3"
                  >
                    编辑
                  </button>
                  <button
                    @click="deleteModel(model.id)"
                    class="text-red-600 hover:text-red-900"
                  >
                    删除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="mt-4 flex justify-end">
          <button
            @click="closeModelModal"
            class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
          >
            关闭
          </button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑模型模态框 -->
    <div v-if="showAddModelModal || showEditModelModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white rounded-lg p-6 w-96">
        <h2 class="text-xl font-semibold mb-4">
          {{ showAddModelModal ? '添加模型' : '编辑模型' }}
        </h2>
        <form @submit.prevent="handleModelSubmit">
          <div class="mb-4">
            <label class="block text-gray-700 text-sm font-bold mb-2">
              模型名称
            </label>
            <input
              v-model="modelFormData.model_name"
              type="text"
              class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm font-bold mb-2">
              模型类型
            </label>
            <select
              v-model="modelFormData.model_type"
              class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            >
              <option value="text">文本</option>
              <option value="image">图像</option>
              <option value="code">代码</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="flex items-center">
              <input
                type="checkbox"
                v-model="modelFormData.is_valid"
                class="form-checkbox h-5 w-5 text-blue-600"
              />
              <span class="ml-2 text-gray-700">是否有效</span>
            </label>
          </div>
          <div class="flex justify-end space-x-3">
            <button
              type="button"
              @click="closeModelFormModal"
              class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
            >
              取消
            </button>
            <button
              type="submit"
              class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
            >
              保存
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const providers = ref([]);
const providerModels = ref([]);
const searchQuery = ref('');
const showAddModal = ref(false);
const showEditModal = ref(false);
const showModelModal = ref(false);
const showAddModelModal = ref(false);
const showEditModelModal = ref(false);
const currentProvider = ref({});
const editingModelId = ref(null);

const formData = ref({
  provider_name: '',
  provider_type: '',
  quota_type: '',
  quota_limit: '',
  is_valid: true
});

const modelFormData = ref({
  model_name: '',
  model_type: '',
  is_valid: true
});

// 获取供应商列表
const fetchProviders = async () => {
  try {
    const response = await axios.get('http://localhost:5001/providers');
    providers.value = response.data;
  } catch (error) {
    console.error('获取供应商列表失败:', error);
  }
};

// 搜索供应商
const handleSearch = async () => {
  try {
    const response = await axios.get('http://localhost:5001/providers', {
      params: { search: searchQuery.value }
    });
    providers.value = response.data;
  } catch (error) {
    console.error('搜索供应商失败:', error);
  }
};

// 添加供应商
const addProvider = async () => {
  try {
    await axios.post('http://localhost:5001/providers', formData.value);
    closeModal();
    fetchProviders();
  } catch (error) {
    console.error('添加供应商失败:', error);
  }
};

// 编辑供应商
const editProvider = (provider) => {
  formData.value = { ...provider };
  showEditModal.value = true;
};

// 更新供应商
const updateProvider = async () => {
  try {
    await axios.put(`http://localhost:5001/providers/${formData.value.id}`, formData.value);
    closeModal();
    fetchProviders();
  } catch (error) {
    console.error('更新供应商失败:', error);
  }
};

// 删除供应商
const deleteProvider = async (id) => {
  if (confirm('确定要删除这个供应商吗？')) {
    try {
      await axios.delete(`http://localhost:5001/providers/${id}`);
      fetchProviders();
    } catch (error) {
      console.error('删除供应商失败:', error);
    }
  }
};

// 显示模型管理
const showModels = async (provider) => {
  currentProvider.value = provider;
  showModelModal.value = true;
  await fetchProviderModels(provider.id);
};

// 获取供应商的模型列表
const fetchProviderModels = async (providerId) => {
  try {
    const response = await axios.get(`http://localhost:5001/provider-models?provider_id=${providerId}`);
    providerModels.value = response.data;
  } catch (error) {
    console.error('获取模型列表失败:', error);
  }
};

// 添加模型
const addModel = async () => {
  try {
    await axios.post('http://localhost:5001/provider-models', {
      ...modelFormData.value,
      provider_id: currentProvider.value.id
    });
    closeModelFormModal();
    fetchProviderModels(currentProvider.value.id);
  } catch (error) {
    console.error('添加模型失败:', error);
  }
};

// 编辑模型
const editModel = (model) => {
  modelFormData.value = { ...model };
  editingModelId.value = model.id;
  showEditModelModal.value = true;
};

// 更新模型
const updateModel = async () => {
  try {
    await axios.put(`http://localhost:5001/provider-models/${editingModelId.value}`, modelFormData.value);
    closeModelFormModal();
    fetchProviderModels(currentProvider.value.id);
  } catch (error) {
    console.error('更新模型失败:', error);
  }
};

// 删除模型
const deleteModel = async (id) => {
  if (confirm('确定要删除这个模型吗？')) {
    try {
      await axios.delete(`http://localhost:5001/provider-models/${id}`);
      fetchProviderModels(currentProvider.value.id);
    } catch (error) {
      console.error('删除模型失败:', error);
    }
  }
};

// 提交表单
const handleSubmit = () => {
  if (showAddModal.value) {
    addProvider();
  } else {
    updateProvider();
  }
};

// 提交模型表单
const handleModelSubmit = () => {
  if (showAddModelModal.value) {
    addModel();
  } else {
    updateModel();
  }
};

// 关闭供应商模态框
const closeModal = () => {
  showAddModal.value = false;
  showEditModal.value = false;
  formData.value = {
    provider_name: '',
    provider_type: '',
    quota_type: '',
    quota_limit: '',
    is_valid: true
  };
};

// 关闭模型管理模态框
const closeModelModal = () => {
  showModelModal.value = false;
  currentProvider.value = {};
  providerModels.value = [];
};

// 关闭模型表单模态框
const closeModelFormModal = () => {
  showAddModelModal.value = false;
  showEditModelModal.value = false;
  modelFormData.value = {
    model_name: '',
    model_type: '',
    is_valid: true
  };
  editingModelId.value = null;
};

onMounted(() => {
  fetchProviders();
});
</script>

<style scoped>
.model-provider-management {
  padding: 20px;
}
</style> 